package com.sisqorap.puzzelalarm;

import com.sisqorap.puzzelalarm.R;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Toast;

public class EndAlarm extends Activity{
    
	private Puzzel puz;
	private int[] puzzelPieces;
	private Toast mToast;
	private MediaPlayer MPX;
	private int puzzlePieces;
	private NotificationManager nm;
    
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Alarm alarm = new Alarm(EndAlarm.this);
		alarm.endWakeUpAlarm();

        nm = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
        String tickerText = this.getString(R.string.repeating_received);
        Notification notif = new Notification(R.drawable.time, tickerText, System.currentTimeMillis());
        
        notif.ledARGB = 0xFFff0000;
        notif.flags = Notification.FLAG_ONGOING_EVENT;
        notif.ledOnMS = 100;
        notif.ledOffMS = 100;
        
        // after a 100ms delay, vibrate for 250ms, pause for 100 ms and
        // then vibrate for 500ms.
        //notif.vibrate = new long[] { 100, 250, 100, 500};
        notif.defaults = Notification.DEFAULT_VIBRATE;
        Intent intent = this.getIntent();
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
        notif.setLatestEventInfo(this, "Puzzel Alarm", "End Alarm", pendIntent);
        nm.notify(0, notif);
        Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); 
	    MPX = new MediaPlayer();
	    try{
		    MPX.setDataSource(this, alert);
		    final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
	        //Log.i("AudioManager", "Audio Manager OK");
	        if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
                MPX.setAudioStreamType(AudioManager.STREAM_ALARM);
			    MPX.prepare();
			    MPX.start();
			    MPX.setLooping(true);
			    MPX.setVolume(50, 50);
	        }
	    }catch(Exception ex){
	    }
	    //Read more: http://www.brighthub.com/mobile/google-android/articles/40735.aspx#ixzz12ttlCuBs
	    boolean testBalls = false;
		if(testBalls){
			setContentView(R.layout.puzzleball);
			puzzleBallView pbv = (puzzleBallView)findViewById(R.id.puzzleBalls);
			if(pbv.getVisibility() == View.GONE){
				finishAlarm();
			}
		}else{
			setContentView(R.layout.endalarm);
			Settings setting = new Settings(this);
			puzzlePieces = setting.getNumberOfPuzzlePieces();
	        puz = new Puzzel(puzzlePieces);
	        
		    puzzelPieces = puz.listPuzzelPieces();
			LinearLayout ll = (LinearLayout)findViewById(R.id.ll_endAlarm);
		    for(int i = 0; i < puzzelPieces.length; i++){
		    	CheckBox cb = new CheckBox(this);
		    	cb.setTextColor(getResources().getColor(R.color.checkBoxColor));
		    	cb.setId(0);
		    	cb.setOnClickListener(new OnClickListener() {
		    	    public void onClick(View v) {
		    	        // Perform action on clicks, depending on whether it's now checked
		    	        if (((CheckBox) v).isChecked() && checkPuzzel(Integer.parseInt(((CheckBox)v).getText().toString()))) {
		    	            ((CheckBox)v).setEnabled(false);
		    	            ((CheckBox)v).setVisibility(View.INVISIBLE);
		    	        }
		    	    }
		    	});
		    	cb.setText(puzzelPieces[i] + "");
		    	cb.setEnabled(true);
		    	ll.addView(cb);
		    }
		    
		}
	}
	
	//Disable the back button so a user can't end the activity
	public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
		}
		return true;
	}
	
	@Override
	public void onDestroy() {
	    //Log.i("EndAlarm", "onDestroy()");
	    super.onDestroy();
	}
	
	@Override
    public void onNewIntent(final Intent newIntent) 
    {
        super.onNewIntent(newIntent);
        //Log.d("EndAlarm","new intent calling me");
        // get and process search query here
        /*final Intent queryIntent = getIntent();
        final String queryAction = queryIntent.getAction();
        if (Intent.ACTION_SEARCH.equals(queryAction)) 
        {
           Log.d("EndAlarm", "new intent for end alarm");
        }
        else {
           Log.d("EndAlarm","new intent NOT end alarm");
        }*/
    }

	private boolean checkPuzzel(int value){
		boolean result = false;
        if(puz.SolveEasyPuzzel(value)){
        	result = true;
			if(puz.isPuzzelSolved()){
				finishAlarm();
        	}
		}
        return result;
	}
	
	private void finishAlarm(){
		if(MPX.isPlaying()){
			MPX.stop();
		}
		nm.cancel(0);
        this.finish();

		// Tell the user about what we did.
        if (mToast != null) {
            mToast.cancel();
        }
        mToast = Toast.makeText(EndAlarm.this, R.string.repeating_unscheduled, Toast.LENGTH_LONG);
        mToast.show();
	}
}